package com.note.gateway.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.note.common.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 网关全局异常处理器
 * 处理网关级别的异常，如路由不存在、服务不可用等
 */
@Slf4j
@Order(-1)
@Component
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        
        // 设置响应的Content-Type为JSON
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        
        // 根据异常类型设置不同的响应状态码和消息
        ResponseVo<?> responseVo;
        
        if (ex instanceof NotFoundException) {
            response.setStatusCode(HttpStatus.NOT_FOUND);
            responseVo = ResponseVo.error(HttpStatus.NOT_FOUND.value(), "服务不存在");
            log.warn("⚠️ 路由匹配失败: {}", ex.getMessage());
        } else if (ex instanceof ResponseStatusException responseStatusException) {
            HttpStatusCode statusCode = responseStatusException.getStatusCode();
            response.setStatusCode(statusCode);
            
            int statusValue = statusCode.value();
            
            if (statusValue == HttpStatus.NOT_FOUND.value()) {
                responseVo = ResponseVo.error(statusValue, "请求的资源不存在");
                log.warn("⚠️ 资源不存在: {}", ex.getMessage());
            } else if (statusValue == HttpStatus.SERVICE_UNAVAILABLE.value()) {
                responseVo = ResponseVo.error(statusValue, "服务暂时不可用，请稍后再试");
                log.error("❌ 服务不可用: {}", ex.getMessage());
            } else if (statusValue == HttpStatus.GATEWAY_TIMEOUT.value()) {
                responseVo = ResponseVo.error(statusValue, "服务请求超时，请稍后再试");
                log.error("❌ 服务超时: {}", ex.getMessage());
            } else if (statusValue == HttpStatus.BAD_GATEWAY.value()) {
                responseVo = ResponseVo.error(statusValue, "服务异常，请稍后再试");
                log.error("❌ 网关错误: {}", ex.getMessage());
            } else if (statusValue == HttpStatus.METHOD_NOT_ALLOWED.value()) {
                responseVo = ResponseVo.error(statusValue, "请求方法不被允许");
                log.warn("⚠️ 方法不允许: {}", ex.getMessage());
            } else {
                responseVo = ResponseVo.error(statusValue, "请求处理失败: " + responseStatusException.getReason());
                log.error("❌ 请求处理异常: {}", ex.getMessage());
            }
        } else {
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            responseVo = ResponseVo.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "网关内部错误");
            log.error("❌ 网关未知异常: ", ex);
        }
        
        // 将ResponseVo转换为JSON并写入响应
        return writeResponse(response, responseVo);
    }
    
    /**
     * 将响应对象写入响应体
     */
    private Mono<Void> writeResponse(ServerHttpResponse response, ResponseVo<?> responseVo) {
        try {
            byte[] bytes = objectMapper.writeValueAsBytes(responseVo);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(buffer));
        } catch (JsonProcessingException e) {
            log.error("响应序列化异常", e);
            byte[] bytes = ("{\"code\":" + responseVo.getCode() + 
                    ",\"status\":false,\"message\":\"" + responseVo.getMessage() + "\"}").getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(buffer));
        }
    }
} 